package models

import (
	"crypto/sha1"
	"fmt"
	"gitchina/kly_service/data"
	_ "gitchina/kly_service/errors"
	"gitchina/kly_service/util"
	_ "github.com/astaxie/beego"
	_ "github.com/pborman/uuid"
	"strings"
	_ "time"
)

type ChatRQ struct {
	SessionKey string `json:"session_key"`
	Offset     int64  `json:"offset"`
	Text       string `json:"text"`
	MessageId  string `json:"message_id"`
	TargetId   string `json:"target_id"`
}

type ChatLog struct {
	Id        int64  `json:"id"`
	Text      string `json:"text"`
	SenderId  string `json:"sender_id"`
	MessageId string `json:"message_id"`
	Time      string `json:"time"`
}

type GetChatContactsRQ struct {
	PageNo   int `json:"page_no"`
	PageSize int `json:"page_size"`
}

type Social struct{}

func (s Social) CreateChatSession(mbrId, targetId string) (sessionKey string, err error) {
	var repo data.SocialRepo
	if strings.Compare(mbrId, targetId) < 0 {
		sessionKey = fmt.Sprintf("%x", sha1.Sum([]byte(fmt.Sprintf("%s%s", mbrId, targetId))))
	} else {
		sessionKey = fmt.Sprintf("%x", sha1.Sum([]byte(fmt.Sprintf("%s%s", targetId, mbrId))))
	}
	if err := repo.AddChatSession(sessionKey, []string{mbrId, targetId}); err != nil {
		util.GetLogger().Error("[model-CreateChatSession] - error:%s", err.Error())
	}
	return
}

func (s Social) AddChatLog(mbrId, sessionKey, text, messageId string) (id int64, err error) {
	var repo data.SocialRepo
	if id, err = repo.AddChatLog(sessionKey, text, mbrId, messageId); err != nil {
		util.GetLogger().Error("[model-AddChatLog] - error:%s", err.Error())
	}
	return
}

func (s Social) GetChatLogs(sessionKey string, offset int64) (rs []ChatLog) {
	var repo data.SocialRepo
	if list, err := repo.GetChatLogs(sessionKey, offset); err == nil {
		rs = make([]ChatLog, len(list))
		for idx, dto := range list {
			rs[idx] = ChatLog{
				Id:        dto.Id,
				Text:      dto.Text,
				Time:      dto.Time,
				SenderId:  dto.SenderId,
				MessageId: dto.MessageId,
			}
		}
	} else {
		util.GetLogger().Error("[model-GetChatLogs] - error:%s", err.Error())
	}
	return
}

func (s Social) GetChatContacts(mbrId string, pageNo, pageSize int) (rs []MemberBriefInfoRS) {
	var mId int64
	var mbrDtoList []data.MemberDto
	var repo data.SocialRepo
	if list, err := repo.GetChatSessions(mbrId, pageNo, pageSize); err == nil {
		ids := make([]int, 0)
		for _, session := range list {
			for _, id := range strings.Split(session.Participants, ",") {
				if mbrId != id {
					if _, _, _, mId, err = (ID(id)).Decode(); err == nil {
						ids = append(ids, int(mId))
					}
				}
			}
		}
		if len(ids) > 0 {
			var mbrRepo data.MemberRepo
			if mbrDtoList, err = mbrRepo.GetMemberBriefInfo(ids); err == nil {
				var memberId ID
				rs = make([]MemberBriefInfoRS, len(mbrDtoList))
				for i, m := range mbrDtoList {
					memberId.Encode(ID_Shard, ID_Ver, ID_Member_Category, int64(m.Id))
					rs[i] = MemberBriefInfoRS{
						Id:       memberId,
						Name:     m.Name,
						NickName: m.NickName,
						PhotoUrl: m.PhotoUrl,
					}
				}
			} else {
				util.GetLogger().Error("[model-GetContactHistory] - error:%s", err.Error())
			}
		}
	} else {
		util.GetLogger().Error("[model-GetChatSessions] - error:%s", err.Error())
	}
	return
}
